﻿using ProjectManage.Core.Enum;
using System.Linq.Dynamic.Core;

namespace ProjectManage.Application.System.Services
{
    [SuppressSniffer]
    public static class ServiceEx
    {
        public static IQueryable<T> DynamicWhere<T>(this IQueryable<T>  query, List<SearchFilterAction> searchFilters) where T : class
        {
            if (!searchFilters.Any()) return query;
            foreach (SearchFilterAction item in searchFilters)
            {
                var expression = $"{item.Name}";
                switch (item.Action)
                {
                    case FilterAction.Equal:
                        expression += "=@0";
                        break;
                    case FilterAction.NotEqual:
                        expression += "!=@0";
                        break;
                    case FilterAction.GreaterThan:
                        expression += ">@0";
                        break;
                    case FilterAction.LessThan:
                        expression += "<@0";
                        break;
                    case FilterAction.LessThanOrEqual:
                        expression += "<=@0";
                        break;
                    case FilterAction.GreaterThanOrEqual:
                        expression += ">=@0";
                        break;
                    case FilterAction.Contains:
                        expression += ".Contains(@0)";
                        break;
                    case FilterAction.NotContains:
                        expression = $"!{expression}.Contains(@0)";
                        break;
                    default:
                        expression += "= @0";
                        break;
                }
                var e = DynamicExpressionParser.ParseLambda(typeof(T), typeof(bool), expression, item.Value);
                query =  query.Where(e);
            }

            return query;
        }
    }
}
